import requests
import json
import submit
import time

start = 1
end = 0
# 请求地址
for index in range(start, end+1):
    baseurl = 'http://acm.nefu.edu.cn/post/explanation/getExplanationList.php?'

    # 请求参数
    params = {
        'problem': index
    }

    # 请求头
    headers = {
        'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3)'
    }

    # 进行请求
    res = ''
    try:
        res = requests.get(baseurl, params=params, headers=headers)
    except:
        print(str(index) + ' not found')
    js = json.loads(res.text)
    jsLen = len(js)
    if jsLen == 0:
        print(str(index) + ' not found')
    # 分析res
    for i in range(0, jsLen):
        explanation = js[i]['explanation']
        flag = 0
        tmp = explanation.split('<pre class="brush:cpp;toolbar:false">')
        if len(tmp) == 1:
            flag = 1
            tmp = explanation.split('```cpp')
        if len(tmp) == 1:
            flag = 2
            tmp = explanation.split('```c++')
        if len(tmp) == 1:
            flag = 3
            tmp = explanation.split('```c')
        if len(tmp) == 1:
            # 没找到
            if i + 1 == jsLen:
                print(str(index) + ' not found')
            continue
        if flag == 0:
            code = tmp[1].split('</pre>')[0]
        else:
            code = tmp[1].split('```')[0]
        code = code.replace('&lt;', '<')
        code = code.replace('&gt;', '>')
        code = code.replace('&nbsp;', ' ')
        code = code.replace('&#39;', "'")
        code = code.replace('&quot;', '"')
        code = code.replace('&amp;', '&')

        # 成功提交
        if submit.submit('your cookie', index, code):
            print(str(index) + ' submit successful')
            time.sleep(5)
            break
        else:
            print(str(index) + ' submit fail')

        # 没找到
        if i + 1 == jsLen:
            print(str(index) + ' not found')

